#!/usr/bin/perl
#
use strict;
use warnings;
use Data::Dumper;
 
binmode STDOUT, ":utf8";
#use utf8;
 
use JSON;
require "doa_subs.pl";

use CGI;
use lib '.';
use users;

my ($username,$level) = &validate;
my ($realm) = get_realm();
my $query = new CGI;
print $query->header;
print $query->start_html('Player List');
print $query->h1('Player List');

############################## Main Prog ##############################
#
# This program will load the existing mapfile.json and allow users to query it
#
#

my $data;
my $outdata={};

my $player_id={};
my $player_name={};
my $playeralt={};
loadPlayers($player_id,$player_name,$playeralt);
my $alliance_id={};
my $alliance_name={};
loadAlliance($alliance_id,$alliance_name);

#print "Loading existing mapfile";
$outdata=loadMAP("mapfile");
#print ".... Loaded\n";

#my $search=<STDIN>;
my %FORM;
foreach my $field ($query->param()) 
{
    $FORM{$field} = $query->param($field);
#	print Dumper(%FORM);
}
my $search=$FORM{search};
chomp $search;
my $altsearch=$search;

$altsearch=lc($altsearch);
#print "$player_name->{$search} is $search\n";
my $pid=$playeralt->{$altsearch}||"0";
if ( $pid eq "0" )
{
	print "Player not Found\n";
	exit;
}
$search=$player_id->{$pid};
print $query->h2("Searching for Player $search");
		
my @pdata;

my $city=$outdata->{'map'}{$pid}{'city'}{'name'}||"";
my $loc=$outdata->{'map'}{$pid}{'city'}{'loc'}||"";
my $clvl=$outdata->{'map'}{$pid}{'city'}{'level'}||"";
my $might=$outdata->{'map'}{$pid}{'player'}{'might'}||"0";
$might=numF($might);
my $allid=$outdata->{'map'}{$pid}{'player'}{'allid'}||"0";
my $alliname=$alliance_id->{$allid}{'name'}||"";
#print "Player $search city $city location $loc level $clvl alliance $alliname\n";
my $tempstring=$query->td($search).$query->td($loc).$query->td($city).$query->td($clvl).$query->td({-align=> "RIGHT"},$might).$query->td($alliname);
push (@pdata, $tempstring);
my $outpostarray=$outdata->{'map'}{$pid}{'outposts'};
foreach my $outpost (keys %{$outpostarray})
{
#	my ($maploc, $cityname, $level, $timestring)=@$outpost;
	my $cityname=$outpost;
	my $maploc=$outpostarray->{$outpost}{'loc'};
	my $level=$outpostarray->{$outpost}{'lvl'};
	my $timestring=$outpostarray->{$outpost}{'ts'};
#	print Dumper($outpost);
	my ($printdate,$printtime)=pdateTime($timestring);
	$tempstring=$query->td(" ").$query->td($maploc).$query->td($cityname).$query->td($level).$query->td(" ").$query->td(" ").$query->td($printdate." ".$printtime);
	push (@pdata, $tempstring);
#	print "$maploc $cityname $level Last update $printdate $printtime\n";
}

print $query->table({-border=>undef,-width=>'100%'},
	$query->Tr({ -align => "CENTER", -valign => "TOP" },$query->th(['Player', 'Location', 'City', 'Level', 'Might', 'Alliance', 'Last Updated'])),
	$query->Tr({ -align => "CENTER", -valign => "TOP" },\@pdata));

print $query->br();
print $query->a( {-href=>"menu.cgi"}, "Main Menu");
print $query->end_html;
